package middleware

import (
	"context"
	"github.com/labstack/gommon/log"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"longmen/server/pkg/common/helper/util"
	"time"
)

type PaymentRequestLimit struct {
	Limit *util.RequestLimitService
}

func NewPaymentRequestLimit() *PaymentRequestLimit {
	r := util.NewRequestLimitService(time.Second, 500000)
	return &PaymentRequestLimit{
		Limit: r,
	}
}

func (r *PaymentRequestLimit) RequestLimit(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	if !r.Limit.IsAvailable() {
		log.Errorf("PaymentRequestLimit 每秒请求超出限制,当前访问次数:%d", r.Limit.ReqCount)
		return nil, status.Errorf(codes.Unauthenticated, "每秒请求超出限制,当前访问次数")
	}
	r.Limit.Increase()
	return handler(ctx, req)
}
